/**
 * 
 */
package com.morningstar.qs.api.basic.common.excel;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * @author justin
 *
 */
public class ExcelServiceImpl implements ExcelService {

	/* (non-Javadoc)
	 * @see com.mstar.excel.ExcelService#makeExcel(com.mstar.excel.ExcelReq)
	 */
	@Override
	public void makeExcel(ExcelReq req) throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();
		List<WorkSheet> list=req.getSheetList();
		
		for(WorkSheet t:list){
			HSSFSheet sheet = workbook.createSheet(t.getName());
			//create title
			HSSFRow row = sheet.createRow((short) 0);
			Iterator<Entry<Integer,String>> itr=t.getTitleMap().entrySet().iterator();
			while(itr.hasNext()){
				Entry<Integer,String> cellItem=itr.next();
				HSSFCell cell = row.createCell(cellItem.getKey());				
				cell.setCellValue(cellItem.getValue());		
				
			}
			// insert row data
			Iterator<Entry<Integer,Map<Integer, String>>> rowItr=t.getRowMap().entrySet().iterator();
			while(rowItr.hasNext()){
				Entry<Integer,Map<Integer, String>> rowItem=rowItr.next();
				row = sheet.createRow(rowItem.getKey());
				
				Iterator<Entry<Integer,String>> cellItr=rowItem.getValue().entrySet().iterator();
				while(cellItr.hasNext()){
					Entry<Integer,String> cellItem=cellItr.next();
					HSSFCell cell = row.createCell(cellItem.getKey());
					Integer colType=t.getColTypeMap().get(cellItem.getKey());
					if( colType!=null){
						transeferDataType(cell,cellItem.getValue(),colType);
					}
					else{
						cell.setCellValue(cellItem.getValue());		
					}
						
				}
				
			}
		}
		
		//write to output
		workbook.write(req.getOutputStream());
		
	}
	
	private void transeferDataType(HSSFCell cell,String value,int colType){
		if(value==null || "NAN".equals(value.toUpperCase())){
			return;
		}
		switch(colType){
		case ExcelService.DTAT_TYPE_DOUBLE:
			cell.setCellValue(Double.parseDouble(value));	
			break;
		case ExcelService.DTAT_TYPE_INT:
			cell.setCellValue(Integer.parseInt(value));	
			break;
		case ExcelService.DTAT_TYPE_STRING:
			cell.setCellValue(value);
			break;
		case ExcelService.DTAT_TYPE_FORMULA:
			cell.setCellFormula(value);
			break;							
		default:
			cell.setCellValue(value);		
			break;							
		}		
	}
	

}
